//
//  RealTimeViewNewController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/7/19.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "RealTimeViewNewController.h"
#import "ArcView.h"
#import <UICountingLabel/UICountingLabel.h>
#import "CommunicationManager.h"
#import "SearchViewController.h"
#import "NSBundle+CurrentLanguage.h"
#import "BTHandler.h"
#import "ChartItem.h"
#import "TrainTargetView.h"
#import "HandBackHandTrainVC.h"
#import "FaQiuTrainController.h"
#import <SoundManager/SoundManager.h>
#import <MediaPlayer/MediaPlayer.h>
#import "RealTimeTrainModel.h"
#import "NSDate+FormateString.h"
#import "DataModel.h"
#import "RealTimeHistoryController.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "NSString+Extension.h"
#import "RealTimeHBIntroController.h"
#import "RealTimeFQReportController.h"
#import "SportViewController.h"
#import "SpeedSoundplayer.h"

@interface RealTimeViewNewController ()<SearchViewControllerDelegate >
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedControl;

@property (weak, nonatomic) IBOutlet UIView *frontView;
@property (weak, nonatomic) IBOutlet UIView *backView;

@property (weak, nonatomic) IBOutlet UIButton *connectButton; // 连接按钮
@property (weak, nonatomic) IBOutlet UIImageView *arrowIcon; // 连接指示箭头
@property (weak, nonatomic) IBOutlet UILabel *tipsLabel; // 未连接指示label

@property (weak, nonatomic) IBOutlet UIButton *reconnectTipsButton; // 重新连接
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *soundButton;

/** MARK-- 底部工具视图 */
@property (weak, nonatomic) IBOutlet UIView *bottomToolView;
@property (weak, nonatomic) IBOutlet UIButton *bottomLeftButton;
@property (weak, nonatomic) IBOutlet UIButton *bottomCenterButton;
@property (weak, nonatomic) IBOutlet UIButton *bottomRightButton;
@property (weak, nonatomic) IBOutlet UIView *historyTipDotView;

/** MARK-- 自定义属性 */
@property (assign, nonatomic) NSInteger page;

@property (nonatomic, strong) NSTimer *linkStateTimer;

@property (nonatomic, assign)BOOL isLinkStateImage;

// 设置目标的弹窗
@property (nonatomic, strong)TrainTargetView *setTargetView;

/** 底部视图水波纹layer */
@property (nonatomic, strong) NSMutableArray *layers;


@property (nonatomic, strong) NSMutableArray <RealTimeTrainModel *>*trainModelArray;


/** 是否有新的历史数据 */
@property (nonatomic, assign)BOOL isHaveHistoryData;

@property (nonatomic, assign)int trainTime;



@end

@implementation RealTimeViewNewController {

//    BOOL _isPlaying;
    BOOL _isConnectPeripheral;
    BOOL _isShowingRealTimePage;
    BOOL _isBegainTrain; // 开始训练
    
    BOOL isAnimation;
    
    dispatch_source_t _timer;
    SearchViewController *_searchViewController;
    HandBackHandTrainVC *_handBackHandconroller; // 正反手控制器
    FaQiuTrainController *_faqiuController; // 发球练习控制
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.scrollView.delaysContentTouches = NO;
    self.scrollView.canCancelContentTouches = YES;
    self.scrollView.scrollEnabled = NO;
    
    self.historyTipDotView.layer.cornerRadius = 3;
    self.historyTipDotView.layer.masksToBounds = YES;
    self.isHaveHistoryData = [DataModel isHaveHistoryData];
    
    
    // 0.读取数据
    
    typeof(self) weakSelf = self;
    dispatch_async(dispatch_queue_create("getrealTimeQueue", DISPATCH_QUEUE_SERIAL), ^{
        
        [weakSelf trainModelArray];
        // 将本地未上传的数据同步到网络
//        [weakSelf needUploadRealtimeTrainData];
        // 将网络上的数据到同步到本地
        [weakSelf synchronizeFQNetWorkDataAndLocationData];
        [weakSelf synchronizeHBNetWorkDataAndLocationData];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.bottomLeftButton.enabled = YES;
            weakSelf.bottomRightButton.enabled = YES;
        });
        
    });

    // 1.国际化
    [self configureLocalization];
    [self registerNotification];
    [self configureTipsShow];
    [self.view bringSubviewToFront:self.soundButton];
    [self enterRealTimeMode];

}

/**
 *  同步网络数据和本地数据
 */
- (void)synchronizeHBNetWorkDataAndLocationData {
    NSString *hbtime = nil;
    if ([DataModel lastHBUploadTime].length < 1 || [DataModel lastHBUploadTime] == nil) {
        hbtime = @"0";
    }else {
        hbtime = [DataModel lastHBUploadTime];
    }
    [YFTrainingApi getTrainRealTimeHistoryData:RealTimeTrainHB withRealTimeDateString:hbtime complete:^(NSArray *realTimeDatas, NSError *error) {
        if (error == nil) {
            [DataModel saveLastRealTimeGetHBUploadTime:[realTimeDatas.lastObject UploadTime]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [realTimeDatas enumerateObjectsUsingBlock:^(RealTimeTrainModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (![[self trainModelStartRealTimeStampArray] containsObject:@(obj.startRealTimeStamp)] && obj.chartItemArray.count > 0) {
                        NSLog(@"%@--%zd", obj, obj.chartItemArray.count);
                        [self.trainModelArray addObject:obj];
                    }
                }];
                [self saveRealTimeTrainData];
            });
        }else {
            NSLog(@"获取实时训练数据失败%@",error);
        }
    }];

}

- (void)synchronizeFQNetWorkDataAndLocationData {
    NSString *fqtime = nil;
    if ([DataModel lastFQUploadTime].length < 1 || [DataModel lastFQUploadTime] == nil) {
        fqtime = @"0";
    }else {
        fqtime = [DataModel lastFQUploadTime];
    }
    [YFTrainingApi getTrainRealTimeHistoryData:RealTimeTrainFQ withRealTimeDateString:fqtime complete:^(NSArray *realTimeDatas, NSError *error) {
        if (error == nil) {
//            NSArray *array = [FQhistoryApi disposeRealTimeTrainModel];
            [DataModel saveLastRealTimeGetFQUploadTime:[realTimeDatas.lastObject UploadTime]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [realTimeDatas enumerateObjectsUsingBlock:^(RealTimeTrainModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (![[self trainModelStartRealTimeStampArray] containsObject:@(obj.startRealTimeStamp)] && obj.chartItemArray.count > 0) {
                        NSLog(@"%@--%zd", obj, obj.chartItemArray.count);
                        [self.trainModelArray addObject:obj];
                    }
                }];
                [self saveRealTimeTrainData];
            });
        }else {
            NSLog(@"获取实时训练数据失败%@",error);
        }
    }];
}


- (NSArray *)trainModelStartRealTimeStampArray {
    NSMutableArray *arrM = [NSMutableArray array];
    [self.trainModelArray enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [arrM addObject:@(obj.startRealTimeStamp)];
        
    }];
    
    return arrM.copy;
}

/**
 *  找出未上传的本地数据,将本地未上传的数据同步到网络
 */
- (void)needUploadRealtimeTrainData {
    
    [self.trainModelArray enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.UploadTime == nil && obj.ID == nil) {
            YFTrainingApi *sendTrainDataApi = [YFTrainingApi uploadTrainRealTimeRecordDataWithTrainDataModel:obj];
            [[YFNetworkingService sharedInstance] sendRequest:sendTrainDataApi callback:^(BOOL success, id result, NSError *error) {
                NSLog(@"%zd",sendTrainDataApi.responseStatusCode);
                if (success) {
                    NSDictionary *dict = sendTrainDataApi.responseJSONObject[@"errDesc"];
                    obj.UploadTime = dict[@"UploadTime"];
                    obj.ID = dict[@"ID"];
                }else {
                    NSLog(@"数据同步到网络失败");
                }
            }];
        }
        
    }];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _isShowingRealTimePage = YES;
    [self enterRealTimeMode];
    [self configureLineState];
   
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.linkStateTimer invalidate];
    [self enterWaitingMode];
    _isShowingRealTimePage = NO;
     self.linkStateTimer = nil;
}

#pragma mark - Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"handBackHandSegue"]) {
        _handBackHandconroller = segue.destinationViewController;
    }else if ([segue.identifier isEqualToString:@"faQiuSegue"]){
        _faqiuController = segue.destinationViewController;
    }else if ([segue.identifier isEqualToString:@"trainHistorySegue"]){
        RealTimeHistoryController *historyVC = segue.destinationViewController;
        historyVC.realTimeTrainHistoryData = self.trainModelArray;
        
        [historyVC setSaveRealTimeTrainModel:^(NSArray<RealTimeTrainModel *> *realTimeTrainData) {
            self.trainModelArray = [NSMutableArray arrayWithArray:realTimeTrainData];
            
             [self saveRealTimeTrainData];
            
//            dispatch_async(dispatch_queue_create("deleteTrainData", DISPATCH_QUEUE_SERIAL), ^{
//                
//                [self saveRealTimeTrainData];
//            });
        }];
    }
}

- (void)configureLocalization {
    
    self.bottomCenterButton.layer.cornerRadius = 15;
    self.bottomCenterButton.layer.masksToBounds = YES;
    
    NSString *imageName = [SpeedSoundplayer shareSpeedSoundplayer].shouldSound ? @"RealTime喇叭-开": @"RealTime喇叭-关";
    [self.soundButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    
    NSString *path = [DataModel writeAndReadRealTimeTargetpathString];
    self.targetValueModel = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (self.targetValueModel == nil) {
        self.targetValueModel = [[RealTimeTrainModel alloc] init];
    }

    [self.segmentedControl setTitle: NSLocalizedString(@"Fore&back Hands", nil) forSegmentAtIndex:0];
    [self.segmentedControl setTitle: NSLocalizedString(@"RealTime.Serve", nil) forSegmentAtIndex:1];
    
    [self.bottomLeftButton setTitle:NSLocalizedString(@"RealTime.Record", nil) forState:UIControlStateNormal];
    [self.bottomRightButton setTitle:NSLocalizedString(@"RealTime.Target", nil) forState:UIControlStateNormal];
    
    [self.bottomCenterButton setTitle:NSLocalizedString(@"Start Training", nil) forState:UIControlStateNormal];
    
    [self.bottomCenterButton setTitle:NSLocalizedString(@"Long press to end", nil) forState:UIControlStateSelected];
    
    
    
    if ([NSBundle currentLanguageIsChinese]) {
        self.bottomCenterButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.reconnectTipsButton setTitle:@"正在重连设备..." forState:UIControlStateNormal];
    }else {
        self.bottomCenterButton.titleLabel.font = [UIFont systemFontOfSize:11];
        [self.reconnectTipsButton setTitle:NSLocalizedString(@"Reconnecting", nil) forState:UIControlStateNormal];
    }
    
}

- (void)enterRealTimeMode {
    
     __weak typeof(self) weakSelf = self;
    
    [[CommunicationManager shareInstance] performOperationType:OperationTypeReadRunTimeData object:nil completionBlock:^(BOOL success, id feedbackData) {
        if (!success) {
            return;
        }
        [BTHandler handleRuntimeData:feedbackData withCompletion:^(BOOL success, SportPoseType actionType, NSInteger speed, NSInteger strength, NSInteger radian, NSInteger hitball, NSInteger topBottomBall, NSInteger forebackBall) {
            if (success) {
                NSLog(@"实时运动模式设置成功");
                ChartItem *item = [[ChartItem alloc] init];
                item.poseType = actionType;
                item.maxSpeed = [NSString stringWithFormat:@"%d",(int)speed];
                item.strength = [NSString stringWithFormat:@"%d",(int)strength];
                item.arc = [NSString stringWithFormat:@"%d",(int)radian];
                item.hasHitTheBall = hitball == 0 ? NO : YES;
                item.handBallType = topBottomBall == 0 ? HandBallTypeUp : HandBallTypeDown;
                item.handDirectionType = forebackBall == 0 ? HandDirectionTypeForeward : HandDirectionTypeBackward;
        
                
                if (self.segmentedControl.selectedSegmentIndex == 0) {
                    //2.播放声音
                    if ([SpeedSoundplayer shareSpeedSoundplayer].shouldSound) {
                        [[SpeedSoundplayer shareSpeedSoundplayer] soundTheSpeed:[item.maxSpeed integerValue]];
                    }
                    
                    //1.将数据保存到当前一次训练的模型中
                    if (_isBegainTrain ) {
                        if (item.poseType == SportPoseTypeXueQiu || item.poseType == SportPoseTypeXuanQiu || item.poseType == SportPoseTypePingJi) {
                             [self.currentTrainModel.chartItemArray addObject:item];
                        }
                    }
                    // 3.将数据传递给正反手训练来刷新界面
                    _handBackHandconroller.chartItem = item;
                    
                }else {
                    
                    if ((item.poseType == SportPoseTypeFaQiu || item.poseType == SportPoseTypeKouSha) ) {
                        
                        if (_isBegainTrain) {
                            [self.currentTrainModel.chartItemArray addObject:item];
                        }
                        
                        if ([SpeedSoundplayer shareSpeedSoundplayer].shouldSound) {
                            [[SpeedSoundplayer shareSpeedSoundplayer] soundTheSpeed:[item.maxSpeed integerValue]];
                        }
                        
                        _faqiuController.chartItem = item;
                    }
                    
                }
                
            }else{
                [weakSelf enterRealTimeMode];
            }
        }];
    }];
}

// 退出实时
- (void)enterWaitingMode {
    
    [[CommunicationManager shareInstance] performOperationType:OperationTypeQuitRunTime object:nil completionBlock:^(BOOL success, id feedbackData) {
        if (success) {
            NSLog(@"退出实时");
        }
    }];

}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"dealloc:%@", self);
    [self.linkStateTimer invalidate];
    self.linkStateTimer = nil;
    
}

#pragma mark - Notification

- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePeripheralConnect:) name:kLGPeripheralDidConnect object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePeripheralDisconnect:) name:kLGPeripheralDidDisconnect object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleBluetoothStatePoweredOff:) name:kLGCentralManagerStatePoweredOffNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adjustingTimeInterval) name:kApplicationWillEnterForeground object:nil];
}

- (void)handlePeripheralConnect:(NSNotification *)notification
{
    if (_isShowingRealTimePage) {
        [self enterRealTimeMode];
    }
    
    [self configureTipsShow];
    [self configureLineState];
    self.reconnectTipsButton.hidden = YES;
}

- (void)handlePeripheralDisconnect:(NSNotification *)notification
{
    [self configureLineState];
    if ([CommunicationManager shareInstance].shouldRetryConnect) {
        self.reconnectTipsButton.hidden = NO;
    }
}

- (void)handleBluetoothStatePoweredOff:(NSNotification *)notification
{
    [self configureLineState];
    [CommunicationManager shareInstance].shouldRetryConnect = NO;
}

#pragma mark - 点击事件
- (IBAction)bottomLeftButtonClick:(UIButton *)sender {
     __weak typeof(self) weakSelf = self;
    if (_isBegainTrain) {
        
        [self alertViewReminderTraining:^{
            
            [weakSelf enterWaitingMode];
            [weakSelf stopRealTimeTrainStopComplete:^{
                self.isHaveHistoryData = NO;
                [weakSelf performSegueWithIdentifier:@"trainHistorySegue" sender:nil];
            }];
           weakSelf.bottomCenterButton.selected = NO;
            
        } Cancel:nil];
        
    }else {
        self.isHaveHistoryData = NO;
        [self performSegueWithIdentifier:@"trainHistorySegue" sender:nil];
    }

}

- (IBAction)bottomCenterButtonClick:(UIButton *)sender {
    
    if (sender.isSelected == NO) {
        
        // 首先判断设备有无连接
        if (![CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
            [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Please Connect the Device", nil) inView:self.view];
            return;
        }
        
        self.toatlTrainTime = 0;
        // 2.底部时间线开始启动
        _isBegainTrain = YES;
        self.fd_interactivePopDisabled = YES;
        // 3.计时器开始启动
        if (self.segmentedControl.selectedSegmentIndex == 0) {
              [_handBackHandconroller endTrain:NO];
            
             _timer = nil;
             [self recordTime];
        }else {
             [_faqiuController endTrain:NO];
            
             _timer = nil;
             [self recordTime];
        }
      
        // 4.开始当前训练的模型RealTimeTrainModel
        if (self.currentTrainModel != nil) {
            self.currentTrainModel = nil;
        }
        self.currentTrainModel = [[RealTimeTrainModel alloc] init];
        self.currentTrainModel.trainTyep = self.segmentedControl.selectedSegmentIndex;
        // 4.1.记录开始训练的时间
        self.currentTrainModel.startRealTimeStamp = [[NSDate date] unixTimeStamp];
        
        [self.trainModelArray addObject:self.currentTrainModel];
        
        [self.bottomLeftButton setTitleColor:kSelectedColor forState:UIControlStateNormal];
        [self.bottomRightButton setTitleColor:kSelectedColor forState:UIControlStateNormal];
        
        self.bottomToolView.backgroundColor = [UIColor whiteColor];
        self.bottomCenterButton.backgroundColor = kSelectedColor;
        sender.selected = YES;
        
    }else {
        if (isAnimation) {
            for (CALayer *layer in self.layers) {
                layer.hidden = YES;
                [layer removeAnimationForKey:@"radar"];
            }
        }else {
            self.bottomCenterButton.selected = NO;
        }
    }
    
}
- (IBAction)bottomCenterBtnTouchDown:(UIButton *)sender {
    
    if (sender.isSelected && isAnimation == NO) {
        for (CALayer *layer in self.layers) {
            [layer removeFromSuperlayer];
            [self.layers removeObject:layer];
        }
        isAnimation = YES;
        [self addAnimation];
    }
    
}

- (IBAction)bottomrRightButton:(UIButton *)sender {
    
    self.bottomToolView.userInteractionEnabled = NO;
    
    UIButton *coverButton = [UIButton buttonWithType:UIButtonTypeCustom];
    coverButton.backgroundColor = [UIColor blackColor];
    coverButton.alpha = 0.5;
    
    [coverButton addTarget:self action:@selector(coverButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    coverButton.frame = self.view.bounds;
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    [window addSubview:coverButton];
    self.setTargetView = [TrainTargetView  trainTargetViewType:self.segmentedControl.selectedSegmentIndex];
    
    __weak typeof(self) weakSelf = self;

    self.setTargetView.frame = CGRectMake(0, kYFScreenHeight, kYFScreenWidth, 355);
    [window addSubview:self.setTargetView];
    
    [self.setTargetView addPopAnimation:self.setTargetView beginTime:CACurrentMediaTime() isUp:YES completeBlock:nil];
    
    [self.setTargetView realTimeTrainHistoryData:self.trainModelArray withTrainType:self.segmentedControl.selectedSegmentIndex];

    [self.setTargetView setSelectTargetValue:^(RealTimeTrainModel *targetValueModel) {

        weakSelf.targetValueModel = targetValueModel;
        // 退出设置页面
        [weakSelf coverButtonClick:coverButton];
    }];

}

- (void)coverButtonClick:(UIButton *)coverButton {
    [coverButton removeFromSuperview];
    self.setTargetView.userInteractionEnabled = NO;
    __weak typeof(self) weakSelf = self;
    
    [self.setTargetView addPopAnimation:self.setTargetView beginTime:CACurrentMediaTime() isUp:NO completeBlock:^{
        weakSelf.bottomToolView.userInteractionEnabled = YES;
        [weakSelf.setTargetView removeFromSuperview];
    }];
}

- (IBAction)soundButtonClick:(UIButton *)sender {
    SpeedSoundplayer *soundPlyer = [SpeedSoundplayer shareSpeedSoundplayer];
    soundPlyer.shouldSound = !soundPlyer.shouldSound;
    NSString *imageName = soundPlyer.shouldSound ? @"RealTime喇叭-开": @"RealTime喇叭-关";
    [sender setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}
- (IBAction)introButtonClick:(UIButton *)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"RealTimeTrainReport" bundle:nil];
    NSString *stroyBoardID = nil;
    self.segmentedControl.selectedSegmentIndex == 0 ? (stroyBoardID = @"RealTimeHBIntro") : (stroyBoardID = @"RealTimeFQIntro");
    UIViewController *vC = [sb instantiateViewControllerWithIdentifier:stroyBoardID];
    [self.navigationController pushViewController:vC animated:YES];
}

- (IBAction)segmentedCotrolValueChanged:(UISegmentedControl *)sender {
    
    if (_isBegainTrain) {
        
        __weak typeof(self) weakSelf = self;
        
        [self alertViewReminderTraining:^{
            [weakSelf stopRealTimeTrainStopComplete:^{
                
                if (sender.selectedSegmentIndex == 0) {
                    [weakSelf  transitionLeft];
                }else {
                    [weakSelf transitionRight];
                    
                }
            }];
            weakSelf.bottomCenterButton.selected = NO;
           
        } Cancel:^{
            sender.selectedSegmentIndex = !sender.selectedSegmentIndex;
        }];
        
    }else {
        if (sender.selectedSegmentIndex == 0) {
            [self  transitionLeft];
        }else {
            [self transitionRight];
            
        }
    }
    

}

// 想右翻转
- (void)transitionRight {
    
    UIViewAnimationOptions transitionDirection =UIViewAnimationOptionTransitionFlipFromRight |UIViewAnimationOptionShowHideTransitionViews;
    [UIView transitionFromView:self.frontView toView:self.backView duration:0.5 options:transitionDirection completion:^(BOOL finished) {
        
    }];
}

// 想左翻转
- (void)transitionLeft {
    UIViewAnimationOptions transitionDirection =UIViewAnimationOptionTransitionFlipFromLeft | UIViewAnimationOptionShowHideTransitionViews;
    
    [UIView transitionFromView:self.backView toView:self.frontView duration:0.5 options:transitionDirection completion:^(BOOL finished) {
    }];
}

/** 弹框提示正在训练 */
- (void)alertViewReminderTraining:(void(^)())onSureAction Cancel:(void(^)())onCancelClick{

    NSString *alertString = NSLocalizedString(@"Confirm to end the training?", nil); //@"训练尚未结束，确定要离开吗？";
    
    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:alertString message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"RealTime.Yes", nil)otherButtonTitles:NSLocalizedString(@"RealTime.No", nil), nil];
    
    [alertView customizeAppearance];
    
    alertView.onOkAction = ^{
        if (onCancelClick != nil) {
            onCancelClick();
        }
    };
    
    [alertView setOnCancelAction:^{
        
        if (onSureAction != nil) {
            onSureAction();
        }
    }];
    
    [alertView show];
}

- (IBAction)backBarButtonClick:(id)sender {
    
    if (_isBegainTrain) {
        
        __weak typeof(self) weakSelf = self;
        
        [self alertViewReminderTraining:^{
            [weakSelf enterWaitingMode];
            [weakSelf stopRealTimeTrainStopComplete:^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }];
         
            weakSelf.bottomCenterButton.selected = NO;
           
        } Cancel:nil];
    }else {
        [self enterWaitingMode];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (IBAction)connectButtonClick:(UIButton *)sender {
    if (![CommunicationManager shareInstance].isCentralReady) {
        return;
    }
    
    if ([CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
        
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Confirm to disconnected device?", nil) message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
        [alertView customizeAppearance];
        
        alertView.onOkAction = ^{
            [[CommunicationManager shareInstance] disconnectThePeripheralWithCompletionBlock:^(BOOL success) {
                if (success) {
                    [CommunicationManager shareInstance].shouldRetryConnect = NO;
                    [self configureTipsShow];
                    [self configureLineState];
                }
            }];
        };
        
        [alertView show];
    } else {
        
        [self showSearchDevicesView];
    }
    
}
/**
 *  显示搜索设备
 */
- (void)showSearchDevicesView {
    if (_searchViewController == nil || _searchViewController.parentViewController == nil) {
        
        [[CommunicationManager shareInstance] stopScanningPeripherals];
        
        SearchViewController *controller = [[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle:nil];
        controller.delegate = self;
        
        [controller presentInParentViewController:self.tabBarController animationType:DetailViewControllerPresentAnimationTypeFade];
        _searchViewController = controller;
    }

}
- (void)configureLineState
{
    if (![CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
        [self.linkStateTimer invalidate];
        self.linkStateTimer = nil;
        _isLinkStateImage = YES;
        [self linkStateTimer];
    }else{
        [_linkStateTimer invalidate];
        self.linkStateTimer = nil;
    }
}
- (void)changeLinkStateImage
{
    NSString *imageName = _isLinkStateImage ? @"sport_icon_device_linked":@"sport_icon_device";
    [self.connectButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    _isLinkStateImage = !_isLinkStateImage;
}

- (void)connectionTipsHidden:(BOOL)hidden {
    NSString *connectionStateImageName = hidden ? @"sport_icon_device_linked" : @"sport_icon_device";
    [self.connectButton setImage:[UIImage imageNamed:connectionStateImageName] forState:UIControlStateNormal];
    self.arrowIcon.hidden = YES;//hidden;
    self.tipsLabel.hidden = YES;//hidden;
}

- (void)configureTipsShow {
    [self connectionTipsHidden:[CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView];
}
//设置时间戳校准
- (void)configureTimeStampSetting
{
    [[CommunicationManager shareInstance] performOperationType:OperationTypeVerify object:nil completionBlock:^(BOOL success, id feedbackData) {
        if (success) {
            [BTHandler handleTimeStampVerifyData:feedbackData withCompletion:^(BOOL successful) {
                if (successful) {
                    NSLog(@"时间校正成功");
                    [self configureHandStyle];
                }
            }];
        }
    }];
}

//连接成功后设置左右手
- (void)configureHandStyle
{
    User *user = [User getLastUser];
    [[CommunicationManager shareInstance] performOperationType:OperationTypeHand object:[NSString stringWithFormat:@"%d", (int)user.userInforItem.hand] completionBlock:^(BOOL success, id feedbackData) {
        if (success) {
            [BTHandler handleHandData:feedbackData withCompletion:^(BOOL success, NSString *hand) {
                if (success) {
                    NSLog(@"设置左右手成功");
                    [self enterRealTimeMode];
                }
            }];
        }
    }];
}

#pragma mark - gcd时间计时器
- (void)recordTime {
    
    if (_timer == nil) {
//        __block int trainTime = 0;
        _trainTime = 0;
        __weak typeof(self) weakSelf = self;
        _trainTime = 0;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        
        dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(_timer, ^{
            if (_isBegainTrain == NO) {
                dispatch_source_cancel(_timer);
                _timer = nil;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    // 记录总的运动时间
                    weakSelf.toatlTrainTime = (NSTimeInterval)_trainTime;
                    
                    _trainTime = 0;
                     [_handBackHandconroller endTrain:YES];
                    [_faqiuController endTrain:YES];
                    if (_segmentedControl.selectedSegmentIndex == 0) {
                        
                        _handBackHandconroller.timeLabel.text = [NSString stringWithTrainTime:_trainTime];
                        _handBackHandconroller.trainTime = _trainTime;
                        
                    }else {
                        
                        _faqiuController.trainTimeLabel.text = [NSString stringWithTrainTime:_trainTime];
                    }
                    
                });
                
            }else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (_segmentedControl.selectedSegmentIndex == 0) {
                        _handBackHandconroller.timeLabel.text = [NSString stringWithTrainTime:_trainTime];
                        _handBackHandconroller.trainTime = _trainTime;
                    }else {
                        _faqiuController.trainTimeLabel.text = [NSString stringWithTrainTime:_trainTime];
                    }

                });
            }
            _trainTime++;
            
        });
        
        dispatch_resume(_timer);
    }

}

// 校准时间
- (void)adjustingTimeInterval {
    
    if (_isBegainTrain) {

        NSTimeInterval currentTime = [[NSDate date] timeIntervalSinceDate:[NSDate dateWithUnixTimeStamp:self.currentTrainModel.startRealTimeStamp]];
        
        double sapceTime = currentTime - (double)self.trainTime;
        if (fabs(sapceTime) >= 2.0) {
            self.trainTime = currentTime;
        }
        
    }
    
}


- (void)setcurentTrainmodelTargetValue {
    
    self.currentTrainModel.frontHandShangXuanTarget = self.targetValueModel.frontHandShangXuanTarget;
    
    self.currentTrainModel.frontHandPingJiTarget = self.targetValueModel.frontHandPingJiTarget;
    self.currentTrainModel.frontHandXueQiuTarget = self.targetValueModel.frontHandXueQiuTarget;
    self.currentTrainModel.frontHandPaiSuTargetSpeed = self.targetValueModel.frontHandPaiSuTargetSpeed;
    
    self.currentTrainModel.backHandShangXuanTarget = self.targetValueModel.backHandShangXuanTarget;
    
    self.currentTrainModel.backHandPingJiTarget = self.targetValueModel.backHandPingJiTarget;
    self.currentTrainModel.backHandXueQiuTarget = self.targetValueModel.backHandXueQiuTarget;
    
    self.currentTrainModel.backHandPaiSuTargetSpeed = self.targetValueModel.backHandPaiSuTargetSpeed;
    self.currentTrainModel.faQiuTargetSpeed = self.targetValueModel.faQiuTargetSpeed;
}



#pragma mark - 数据存储与获取
-(void)saveRealTimeTrainData {

    NSString *path = [DataModel writeAndReadRealTimeTrainDataPathString];
    
    [NSKeyedArchiver archiveRootObject:self.trainModelArray toFile:path];
}

#pragma mark - 懒加载

- (void)setTargetValueModel:(RealTimeTrainModel *)targetValueModel {
    _targetValueModel = targetValueModel;
    _handBackHandconroller.targetModel = targetValueModel;
    _faqiuController.targetModel = targetValueModel;
}

- (NSTimer *)linkStateTimer {
    if (_linkStateTimer == nil) {
        _linkStateTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeLinkStateImage) userInfo:nil repeats:YES];
        
        [[NSRunLoop mainRunLoop] addTimer:_linkStateTimer forMode:NSRunLoopCommonModes];
    }
    
    return _linkStateTimer;
}

- (NSMutableArray *)trainModelArray {
    if (_trainModelArray == nil) {
        //1.缓存路径
        NSString *path = [DataModel writeAndReadRealTimeTrainDataPathString];
        //2.读取缓存
        _trainModelArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

        //第一次安装的时候,解档出来的数组是空的,就必须要做一步判断
        if (_trainModelArray == nil) {
            _trainModelArray = [NSMutableArray array];
        }
        
    }
    return _trainModelArray;
}
- (NSMutableArray *)layers {
    if (_layers == nil) {
        _layers = [NSMutableArray array];
    }
    return _layers;
}

- (void)setIsHaveHistoryData:(BOOL)isHaveHistoryData {
    _isHaveHistoryData = isHaveHistoryData;
    [DataModel setIsHaveHistory:isHaveHistoryData];
    self.historyTipDotView.hidden = !isHaveHistoryData;
}

#pragma mark - 水波纹动画
- (void)addAnimation {
    
    NSArray *array = @[[UIColor colorWithHex:0x25c9ad alpha:0.3],[UIColor colorWithHex:0x25c9ad alpha:0.7], kSelectedColor];
    
    for (NSInteger i = 0; i < 3; i++) {
        
        [self addAnimation:self.bottomToolView beginTime:CACurrentMediaTime() + i * 0.3 withRect:CGRectMake(0, 0, kYFScreenWidth, 48) borderColor:array[i] forKey:[self layerIndentify:i]];
    }
    
}
- (NSString *)layerIndentify:(NSInteger)index {
    switch (index) {
        case 0:
            return @"outLayer";
            break;
        case 1:
            return @"middleLayer";
            break;
        case 2:
            return @"centerLayer";
            break;
            
        default:
            return nil;
            break;
    }
}
- (void)addAnimation:(UIView *)inView beginTime:(double)beginTime withRect:(CGRect)rect borderColor:(UIColor *)color forKey:(NSString *)keyPath {
    
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(-rect.size.width * 0.1, 0, rect.size.width * 1.2 , rect.size.height);
    layer.borderColor = color.CGColor;
    layer.borderWidth = rect.size.height * 0.5;
    layer.cornerRadius = rect.size.height /2;
    
    CAAnimationGroup *groupAnimation = [CAAnimationGroup animation];
    groupAnimation.fillMode = kCAFillModeBackwards;
    groupAnimation.removedOnCompletion = NO;
    groupAnimation.beginTime = beginTime;
    groupAnimation.duration = 1.0;
    
    
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.x"];
    scaleAnimation.autoreverses = NO;
    scaleAnimation.fromValue = @0;
    scaleAnimation.toValue = @1.2;
    
    CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.values = @[@1];
    opacityAnimation.keyTimes = @[@0, @0.5, @1];
    
    groupAnimation.animations = @[scaleAnimation, opacityAnimation];
    
    [groupAnimation setValue:layer forKey:@"layerIndentify"];
    
    groupAnimation.delegate = self;
    [self.layers addObject:layer];
    
    [layer addAnimation:groupAnimation forKey:@"radar"];
    
    [inView.layer insertSublayer:layer atIndex:0];
    
}
- (void)animationDidStop:(CABasicAnimation *)anim finished:(BOOL)flag {
    
    if (flag == YES) {
        CALayer *layer = [anim valueForKey:@"layerIndentify"];
        
        [layer removeAnimationForKey:@"radar"];
        
        [layer removeFromSuperlayer];
        
        [self.layers removeObject:layer];
        
        if (self.bottomCenterButton.isSelected && isAnimation) {

            [self stopRealTimeTrainStopComplete:nil];
        }
        
    }else {
        CALayer *layer = [anim valueForKey:@"layerIndentify"];
        [layer removeFromSuperlayer];
        [self.layers removeObject:layer];
        isAnimation = NO;
    }
    
}

/**
 *  停止实时训练
 */
- (void)stopRealTimeTrainStopComplete:(void(^)())StopComplete {
    
    [self.bottomCenterButton setTitleColor:kSelectedColor forState:UIControlStateHighlighted];
    self.bottomCenterButton.backgroundColor = [UIColor whiteColor];
    self.bottomToolView.backgroundColor = kSelectedColor;
    
    [self.bottomLeftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.bottomRightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    // 保存结束的时间戳
    self.currentTrainModel.endRealTimeStamp = [[NSDate date] unixTimeStamp];
    [self setcurentTrainmodelTargetValue];
      // 计算完成度
   
    if (self.currentTrainModel.chartItemArray.count > 0) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"RealTime.Is save training data...", nil) inView:self.view];
        
        YFTrainingApi *sendDataApi = [YFTrainingApi uploadTrainRealTimeRecordDataWithTrainDataModel:self.currentTrainModel];
        [[YFNetworkingService sharedInstance] sendRequest:sendDataApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                NSDictionary *dict = sendDataApi.responseJSONObject[@"errDesc"];
                self.currentTrainModel.UploadTime = dict[@"UploadTime"];
                self.currentTrainModel.ID = dict[@"ID"];
            }else {
                NSLog(@"训练数据上传失败");
            }
        }];
        
        [self.currentTrainModel calculateCopleteSituation];
        [self saveRealTimeTrainData];

    }else {
        [self.trainModelArray removeObject:self.currentTrainModel];
    }

    isAnimation = NO;
    // 1.计时器结束
    _isBegainTrain = NO;
    // 开启右滑退出
    self.fd_interactivePopDisabled = NO;
    
    CGFloat afterTime = 2.0;
    
    if (self.currentTrainModel.chartItemArray.count > 100) {
        afterTime = 3.0;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(afterTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (self.currentTrainModel.chartItemArray.count > 0) {
            self.isHaveHistoryData = YES;
        }
       
        // 结束训练，发送通知刷新主界面数据
        [[NSNotificationCenter defaultCenter] postNotificationName:SportViewControllerShouldRefreshNotification object:nil];
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (StopComplete != nil) {
            StopComplete();
        }
        
    });
    

}

#pragma mark - SearchViewControllerDelegate
- (void)searchViewControllerDidConnectPeripheral:(SearchViewController *)controller {
    [self configureTimeStampSetting];
    [self configureTipsShow];
    [self configureLineState];
}

@end

